﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using HNAlbum.Logic.Entity;

namespace HNAlbum.Component.NivoSlider
{
    /// <summary>
    /// Implement a Nivo Slider http://nivo.dev7studios.com/
    /// </summary>
    public class NivoSlider : Panel
    {
        #region Private fields
        private Panel _nivoSlider = null;
        public const int PHOTO_PER_PAGE = 32;
        public int PhotoCount { get; set; }
        #endregion
        /// <summary>
        /// Default Nivo Slider constructor
        /// </summary>
        public NivoSlider()
        {
            this.Attributes.Add("id", "slider_wrapper");
            _nivoSlider = new Panel();
            this.Controls.Add(_nivoSlider);
            _nivoSlider.Attributes.Add("id", "slider");
            _nivoSlider.Attributes.Add("class", "nivoSlider");
        }

        /// <summary>
        /// Instanciate a Nivo Slider and load a gallery
        /// </summary>
        /// <param name="albumId">Album Id</param>
        /// <param name="albumPage">The page to show</param>
        public NivoSlider(string albumId, int albumPage)
            : this()
        {
            try
            {
                LoadAlbum(albumId, albumPage);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Load a specific gallery to the slider
        /// </summary>
        /// <param name="albumId">The album Id</param>
        /// <param name="albumPage">Album active page</param>
        public void LoadAlbum(string albumId, int albumPage)
        {
            try
            {
                HNAlbumData album = new HNAlbumData(albumId);
                album.Load();
                //TotalPhotos = album.Photos.Count;
                PhotoCount = album.PhotoCollection.Count;

                //Calculate which photos to be displayed on this page
                int startItemIndex = (albumPage - 1) * PHOTO_PER_PAGE;
                int endItemIndex = startItemIndex + PHOTO_PER_PAGE;
                if (endItemIndex > PhotoCount)
                {
                    endItemIndex = PhotoCount;
                }

                for (int i = startItemIndex; i < endItemIndex; i++)
                {
                    //HNAlbumPhoto photo = album.Photos[i];
                    HNAlbumPhoto photo = album.PhotoCollection.ElementAt(i).Value;
                    NivoSliderItem nivoItem = new NivoSliderItem(photo.Url, photo.Caption);
                    _nivoSlider.Controls.Add(nivoItem);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}